<?php
/**
 * File: ManageController.php.
 * User: Yan<me@xiaoyan.me>
 * DateTime: 2017-12-23 0:52
 */

namespace App\Controller;


use App\Core\Request;
use App\Core\WebController;
use App\Models\UserInfo;
use App\Models\VoteAdminSession;
use App\Models\VoteInfo;
use App\Models\VoteProject;

class ManageController extends WebController
{
    const ADMIN_KEY = 'manage_admin';
    const ALLOW_LOGIN_TIME = 60;

    public function index(Request $request)
    {
        $adminData = $this->getAdminData();
        if (!$adminData) {
            jump('/admin/login');
        }
        $page_view = $request->get('page_view');
        if (method_exists($this, $page_view)) {
            call_user_func([$this, $page_view], $request);
            return;
        }
        if ($request->get('action') == 'role') {
            $uid = $request->getInt('uid');
            $role = $request->get('role');
            if ($uid < 1) ajaxError('操作用户不存在');
            if ($role == 'admin' || !in_array($role, array_keys(UserInfo::$UserRoles))) ajaxError('该操作不被允许');
            $user = new UserInfo();
            $user->update(['user_role' => $role], ['uid' => $uid]);
            if ($user->hasError()) ajaxError('操作失败，请重试');
            ajaxSuccess();
        }
        if ($request->get('action') == 'avatar') {
            $user = new UserInfo();
            $uid = $request->getInt('uid');
            $user->update(['user_avatar' => $request->post('src')], ['uid' => $uid]);
            if ($user->hasError()) ajaxError('操作失败，请重试');
            ajaxSuccess();
        }
        $page_size = 20;
        $page_index = $request->getInt('page');
        $page_index = $page_index < 1 ? 1 : $page_index;
        $user = new UserInfo();
        $total = $user->count('uid', ['state' => 1]);
        $this->assign('user_list', $user_list = $user->select('*', [
            'AND' => ['state' => 1],
            'LIMIT' => [($page_index - 1) * $page_size, $page_size],
            'ORDER' => ['uid' => 'ASC']
        ]));
        $this->assign('user', $adminData);
        $this->assign('total', $total);
        $this->assign('page_index', $page_index);
        $this->assign('role_list', UserInfo::$UserRoles);
        $this->assign('total_page', ceil($total / $page_size));

        $this->render('manage', []);
    }

    private function addView(Request $request)
    {
        if ($request->get('action') == 'save') {
            $vote = new VoteInfo();
            if ($vote->insert($request->posts()) > 0) {
                jump('/admin/');
            }
            $this->message('错误了');
        }

        $pro = new VoteProject();
        $this->assign('pro_list', $pro->select('*'));
        $this->render('add-vote');
    }

    private function getAdminData()
    {
        $admin_id = isset($_SESSION[self::ADMIN_KEY]) ? $_SESSION[self::ADMIN_KEY] : null;

        if (!$admin_id) return null;
        $admin = new VoteAdminSession();
        $adminData = $admin->find($admin_id);
        if ($adminData['state'] == VoteAdminSession::Logged && $adminData['uid'] > 0) {
            $user = new UserInfo();
            return $user->find($adminData['uid']);
        }
        return null;
    }

    public function login(Request $request)
    {
        if ($request->get('act') == 'data') {
            //暂时不允许账号登录
        }
        $admin = new VoteAdminSession();
        $session_id = session_id();
        $data = ['session_id' => $session_id];
        $adminData = $admin->find($session_id);
        if ($adminData['state'] == VoteAdminSession::Logged && $this->getAdminData()) {

            jump('/admin/');
        }
        if ($adminData) {
            $admin->update(['state' => VoteAdminSession::Not_scanned, 'uid' => 0], $data);
        } else {
            $admin->insert($data);
        }
        if (isset($_SESSION[self::ADMIN_KEY])) {
            $_SESSION[self::ADMIN_KEY] = null;
            unset($_SESSION[self::ADMIN_KEY]);
        }
        $this->assign('session_id', $session_id);
        $check_url = SITE_URL . '/admin/wechat_login_check?key=' . $session_id;
        $_SESSION['login_time'] = time();
        $this->render('login', ['check_url' => $check_url], false);
    }

    public function wechatLogin(Request $request)
    {
        if (!isset($_SESSION['login_time'])) $_SESSION['login_time'] = 0;
        $session_id = $request->get('key');
        if (!$session_id) $this->message('错误的参数(session_id)');
        $admin = new VoteAdminSession();
        $adminData = $admin->find($session_id);
        if (!$adminData) {
            ajaxError('登录的数据不存在');
        }
        if ($request->get('action') == 'check') {
            header('Access-Control-Allow-Origin : *');
            if ($_SESSION['login_time'] - time() > self::ALLOW_LOGIN_TIME) {
                ajaxError('<i class="icon_msg_mini warn"></i> 该二维码登录信息已失效
<p>您可以<a href="javascript:location.reload();">刷新二维码</a>重新扫描验证，或关闭窗口</p>');
            }
            if ($adminData['state'] == VoteAdminSession::Logged) {
                $user = new UserInfo();
                $userData = $user->find($adminData['uid']);
                if (!$userData || $userData['user_role'] != 'admin') {
                    ajaxError('<i class="icon_msg_mini warn"></i> 验证微信用户权限不足
<p>您可以<a href="javascript:location.reload();">刷新二维码</a>重新扫描验证，或关闭窗口</p>');
                }
                $_SESSION[self::ADMIN_KEY] = $session_id;//设置登录标记
                $_SESSION[WX_USER_KEY] = $userData['user_open_id']; // 设置微信标记
            }
            ajaxSuccess($adminData['state']);
        }

        if (!$request->user || $request->user->user_role != 'admin') {
            $this->warn('您的微信还没有绑定账号或者绑定的账号不是特殊用户');
        }
        $data = ['session_id' => $session_id];
        if ($_SESSION['login_time'] - time() > self::ALLOW_LOGIN_TIME) {
            $this->warn('该登录信息已过期请重新扫描二维码');
        }
        if ($request->get('action') == 'process') {
            //考虑允许操作
            $type = $request->get('type');
            if (!in_array($type, ['ok', 'cancel'])) $this->message('改操作不被认可,请返回重新操作');
            $admin->update([
                'uid' => $request->user->uid,
                'state' => $type == 'ok' ? VoteAdminSession::Logged : VoteAdminSession::Failed
            ], $data);
            $this->message($type == 'ok' ? '您已确认了此次登录' : '您已取消了此次登录');
        }
        $admin->update(['state' => VoteAdminSession::Scanned], $data);
        $this->render('qr_code_check', $data);
    }
}